'use strict';

const { Service } = require('egg');
const sha1 = require('sha1')
class UserService extends Service {

  /**
   * 用户注册
   * @param {object} data
   * @return
   */
  async register(data) {
    const { ctx } = this;
    const { model } = ctx;
    const { username, password, avatar = '' } = data;
    // 给密码加密
    const _password = sha1(password)
    const findUser = await model.User.findOne({ username })
    if (findUser) ctx.throw(401, '用户已经存在，请重新选择用户名注册')
    return await model.User.create({ username, password: _password, avatar });
  }

  /**
   * 用户登录
   * @param {object} data 
   * @returns 
   */
  async login(data) {
    const { ctx } = this
    const { model } = ctx
    const { username, password } = data
    const _password = sha1(password)
    const userinfo = await model.User.findOne({ username, password: _password })
    if (!userinfo) ctx.throw(401, '用户名或者密码错误')
    return userinfo
  }

  /**
   * 检测用户名是否存在
   * @param {string} username 
   * @returns 
   */
  async checkUsername(username) {
    const { ctx } = this
    const { model } = ctx
    const findUser = await model.User.findOne({ username })
    if (findUser) return true
    return false
  }

  /**
   * 更新用户信息
   * @param {string} id 
   * @param {object} data 
   * @returns 
   */
  async update(id, data) {
    const { ctx } = this
    const { model } = ctx
    const { password } = data
    const _password = sha1(password)
    return await model.User.findByIdAndUpdate(id, { ...data, password: _password }, {
      new: true,
    })
  }

  /**
   * 获取用户列表
   * @param {number} page 
   * @param {number} pageSize 
   * @returns 
   */
  async list(page, pageSize) {
    const { ctx } = this
    const { model } = ctx
    const count = await model.User.count({})
    const data = await model.User.find({}).limit(pageSize).skip((page - 1) * pageSize)
    return { count, data }
  }

  /**
   * 获取某个用户信息
   * @param {string} id 
   * @returns 
   */
  async findById(id) {
    const { ctx } = this
    const { model } = ctx
    const user = await model.User.findById(id)
    if (!user) ctx.throw(401, '用户不存在')
    return user
  }
}

module.exports = UserService;
